package com.doyutu.seed.common.impl;

import com.doyutu.seed.common.LRUCache;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @author DoyuTu
 * @version 0.0.1
 * spring-boot-project-seed
 * LRU算法Map，不会扩容
 * size > max 触发淘汰
 * 建议使用Guava或者Caffeine实现
 * {@link com.doyutu.seed.utils.CacheUtil}
 */
@Deprecated
public class LRUMapImpl extends LinkedHashMap implements LRUCache {

    private final int max;
    private final Object lock;

    public LRUMapImpl(int max, Object lock) {
        //无需扩容
        super((int) (max * 1.4f), 0.75f, true);
        this.max = max;
        this.lock = lock;
    }

    /**
     * 重写LinkedHashMap的removeEldestEntry方法即可
     * 在Put的时候判断，如果为true，就会删除最老的
     * @param eldest
     * @return
     */
    @Override
    protected boolean removeEldestEntry(Map.Entry eldest) {
        return size() > max;
    }

    @Override
    public Object getValue(Object key) {
        synchronized (lock) {
            return get(key);
        }
    }

    @Override
    @SuppressWarnings({"unchecked"})
    public void putValue(Object key, Object value) {
        synchronized (lock) {
            put(key, value);
        }
    }


    @Override
    public boolean removeValue(Object key) {
        synchronized (lock) {
            return remove(key) != null;
        }
    }

    @Override
    public boolean removeAll(){
        clear();
        return true;
    }
}
